import cheerio from 'cheerio';
import { Anaylzer } from './crowller';

interface Tile {
    link: string,
    title: String
}

interface Artile {
    title?: string,
    content?: string
}

export default class BiqugeAnaylzer implements Anaylzer {
    private static instance: BiqugeAnaylzer;
    static getInstance() {
        if (!BiqugeAnaylzer.instance) {
            BiqugeAnaylzer.instance = new BiqugeAnaylzer();
        }
        return BiqugeAnaylzer.instance;
    }
    private getJsonInfo(html: string): Tile[] {
        const titles: Tile[] = [];
        const $ = cheerio.load(html);
        const items = $('#list > dl > dd > a');
        items.map((index, element) => {
            const title = $(element).text();
            const link = $(element).attr('href')?.toString() ?? '';
            titles.push({ link, title });
        })
        return titles;
    }
    public anaylzer(html: string) {
        const result = this.getJsonInfo(html);
        return JSON.stringify(result);
    }
    private constructor() { }
}


export class DetailAnaylzer implements Anaylzer {
    private static instance: DetailAnaylzer;
    static getInstance() {
        if (!DetailAnaylzer.instance) {
            DetailAnaylzer.instance = new DetailAnaylzer();
        }
        return DetailAnaylzer.instance;
    }
    private getJsonInfo(html: string): Artile {
        const $ = cheerio.load(html);
        const content = $('#content').text();
        const title = $('.bookname > h1').text();
        return {
            title: title,
            content: content
        };
    }
    public anaylzer(html: string) {
        return JSON.stringify(this.getJsonInfo(html));
    }
    private constructor() { }
}